package com.yupi.picturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import com.yupi.picturebackend.exception.ThrowUtils;
//import com.yupi.picturebackend.manager.sharding.DynamicShardingManager;
import com.yupi.picturebackend.model.dto.space.SpaceAddRequest;
import com.yupi.picturebackend.model.dto.space.SpaceQueryRequest;

import com.yupi.picturebackend.model.entity.Space;
import com.yupi.picturebackend.model.entity.SpaceUser;
import com.yupi.picturebackend.model.entity.User;
import com.yupi.picturebackend.model.enums.SpaceLevelEnum;

import com.yupi.picturebackend.model.enums.SpaceRoleEnum;
import com.yupi.picturebackend.model.enums.SpaceTypeEnum;
import com.yupi.picturebackend.model.vo.SpaceVO;
import com.yupi.picturebackend.model.vo.UserVO;
import com.yupi.picturebackend.service.SpaceService;
import com.yupi.picturebackend.mapper.SpaceMapper;
import com.yupi.picturebackend.service.SpaceUserService;
import com.yupi.picturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Slf4j
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    @Resource
    UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SpaceUserService spaceUserService;
       //为了方便部署，注释掉分表
//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;

    /**
     * 创建空间
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
        @Override
        public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
//            1）填充参数默认值
            //转换实体类和DTO
            Space space = new Space();
            BeanUtils.copyProperties(spaceAddRequest, space);
            if (StrUtil.isBlank(space.getSpaceName())){
                space.setSpaceName("默认空间");
            }
            if (space.getSpaceLevel() ==null){
                space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
            }
            if (space.getSpaceType() ==null){
                space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
            }
            //填充容量和大小
            this.fillSpaceBySpaceLevel(space);
//            2）校验参数
             this.validSpace(space,true);
//            3）校验权限，非管理员只能创建普通级别的空间
            Long userId = loginUser.getId();
            space.setUserId(userId);
            if (SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel()&&!userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限创建指定级别的空间");
            }
//            4）同一个账号自能创建一个私有空间以及一个团队空间
            String lock = String.valueOf(userId).intern();
            synchronized (lock){
                Long newSpaceId = transactionTemplate.execute(status -> {
                    //判断是否已有空间
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    //如果已经有空间，就不能再创建
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每个用户每类空间只能创建一个");
                    //创建
                    boolean result = this.save(space);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "保存空间到数据库失败");
                    //创建成功后如果是团队空间，关联新增团队成员记录
                    if (SpaceTypeEnum.TEAM.getValue() == space.getSpaceType()){
                            SpaceUser spaceUser = new SpaceUser();
                            spaceUser.setUserId(userId);
                            spaceUser.setSpaceId(space.getId());
                            spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                            result = spaceUserService.save(spaceUser);
                            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                    }
//                    //创建分表（仅对团队空间生效），为方便部署暂时不使用
//                     dynamicShardingManager.createSpacePictureTable(space);
                    //返回新写入的数据id
                    return space.getId();
                });
               return Optional.ofNullable(newSpaceId).orElse(-1L);
            }
        }

        @Override
        public void validSpace(Space space, boolean add) {
            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
            // 从对象中取值
            String spaceName = space.getSpaceName();
            Integer spaceLevel = space.getSpaceLevel();
            Integer spaceType = space.getSpaceType();
            SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
            SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
            //校验参数
            // 要创建
            if (add) {
                if (StringUtils.isBlank(spaceName)) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
                }
                if (spaceLevel == null) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
                }
                if (spaceType == null) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类别不能为空");
                }
            }
            //修改时，空间名称进行校验
            if (StringUtils.isNotBlank(spaceName) && spaceName.length() > 30) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
            }
            //修改时空间级别进行校验
            if (spaceLevel!=null && spaceLevelEnum==null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
            }
            //修改数据时，空间级别进行校验
            if (spaceLevel != null && spaceLevelEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
            }
            //修改数据时，空间类别进行校验
            if (spaceType != null && spaceTypeEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类别不存在");
            }
        }

        @Override
        public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
            // 对象转封装类
            SpaceVO spaceVO = SpaceVO.objToVo(space);
            // 关联查询用户信息
            Long userId = space.getUserId();
            if (userId != null && userId > 0) {
                User user = userService.getById(userId);
                UserVO userVO = userService.getUserVO(user);
                spaceVO.setUser(userVO);
            }
            return spaceVO;
        }

        @Override
        public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
            List<Space> spaceList = spacePage.getRecords();
            Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
            if (CollUtil.isEmpty(spaceList)) {
                return spaceVOPage;
            }
            // 对象列表 => 封装对象列表
            List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
            // 1. 关联查询用户信息
            Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
            Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                    .collect(Collectors.groupingBy(User::getId));
            // 2. 填充信息
            spaceVOList.forEach(spaceVO -> {
                Long userId = spaceVO.getUserId();
                User user = null;
                if (userIdUserListMap.containsKey(userId)) {
                    user = userIdUserListMap.get(userId).get(0);
                }
                spaceVO.setUser(userService.getUserVO(user));
            });
            spaceVOPage.setRecords(spaceVOList);
            return spaceVOPage;
        }

        @Override
        public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
            QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
            if (spaceQueryRequest == null) {
                return queryWrapper;
            }
            // 从对象中取值
            Long id = spaceQueryRequest.getId();
            Long userId = spaceQueryRequest.getUserId();
            String spaceName = spaceQueryRequest.getSpaceName();
            Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
            Integer spaceType = spaceQueryRequest.getSpaceType();
            String sortField = spaceQueryRequest.getSortField();
            String sortOrder = spaceQueryRequest.getSortOrder();
           //拼接查询条件


            queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
            queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
            queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
            queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
            queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
            // 排序
            queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
            return queryWrapper;
        }

        @Override
        public void fillSpaceBySpaceLevel(Space space) {
            // 根据空间级别，自动填充限额
            SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅本人或管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }
}







